// 错误函数
var _errors = {
	template: function(type) {
		var _type = type;
		imgSrc = _type? '../../css/images/error/error1.png' : '../../css/images/error/error2.png';
		// 网络请求异常，请检查您的手机是否联网
		return '<div id="error_msg" class="active">\
                        <div class="errorpane ub-ver">\
                            <img src="'+imgSrc+'" class="errorimg ub ub-ac"/>\
                        </div>\
                        <p class="errorp txt-c"></p>\
                    </div>';
	},
	check: function(type) {
		if(!$('#error_msg')[0])
			$('.scrollbox').append(this.template(type));
	},
	show: function(_msg, isShowPanel, type) {
		var self = this,
			_type = type,
			errorJQ = $('#error_msg');
			
			// 隐藏正在加载
			$('#dragmore').remove();
			endPullDownRefreshLately(100);
			
			if(!isShowPanel){
				_errors.hide();
				return;
			}
			
			/*if($('body').hasClass('bc-bg')){
				$('body').addClass('bg-wh');
			}*/
			self.check(_type);
			$('.errorp').text(_msg);
			Load.finish();
	},
	hide: function() {
		/*if($('body').hasClass('bc-bg') &&　$('body').hasClass('bg-wh')){
			$('body').removeClass('bg-wh');
		}*/
		this.check();
		$('#error_msg').remove();
	}
};

function global_error(err, type) {
	Load.finish(); // 关闭loading
	
	err = err || {};
	if(type) type = 0;
	if(err && err.readyState == 4) {
		if(err.status == 200) {
			if(type == 0)
				toast('数据请求异常，请联系管理员');
			else{
				_errors.show('数据请求异常，请联系管理员', true, true);
			}
		} else {
			if(type == 0)
				toast('无网络，请检查网络');
			else{
				_errors.show('无网络，请检查网络', true, true);
			}
		}
	} else {
		if(err && err.readyState == 0 &&　err.status ==　0){
			if(type == 0)
				toast('无网络，请检查网络');
			else{
				_errors.show('无网络，请检查网络', true, true);
			}
		}
		
		if(err.status == 'false') {
			_errors.show('数据请求异常，请联系管理员', true, true);
		} else if(err.code) {
			toast(err.codemsg, 2000, 'middle', 0);
		} else {
			_errors.hide();
		}
	}
};

// ajax参数、返回数据拦截、打印日志
var ajaxUrl = {};
var _ajax = $.ajax,
	_ajaxMethod = {
		debug: AJAX_DEBUG,
		param: {},
		paramCache: {},
		successCallback: function(args) {
			var param = this.param,
				paramCache = this.paramCache;
			if(args && args.length) {
				if(args[2].status == 200) {
					if(args[0] && args[0].code == "0") {
						utils.handleImgEmpty();
						_errors.hide();
					}
					var successData = args[0];
					// console.log(param.data);
					if(parseInt(successData.error_no)) {
						_ajaxMethod.debug && console.error(JSON.stringify(args[0]));
					} else {
						_ajaxMethod.debug && console.log('success data: ', args[0]);
					}
				} else {
					_ajaxMethod.debug && console.log('error data', args[1], args[3].responseError);
				}
			} else {
				_ajaxMethod.debug && console.log('success\'s return value was empty');
			}
			paramCache.success.apply(param.success, args)
		},
		errorCallback: function(args) {
			// console.log(args);
			var arg = Array.prototype.slice.call(args) || [],
				param = this.param,
				paramCache = this.paramCache;
			if(arg.length && arg[1] == 'timeout') {
				appcan.window.openToast("网络超时！", 2000);
			} else {
				paramCache.error.apply(param.error, args);
			}
			Load.finish();
			this.finish();
			
			setTimeout(function() {
				// toast('数据加载失败，请下拉刷新重试', 'middle', 0);
			}, constant.ajaxDelay + 100);
		},
		completeCallback: function(args) {
			var param = this.param,
				paramCache = this.paramCache;
			paramCache.complete.apply(param.complete, args);
			_ajaxMethod.finish();
		},
		finish: function() {
			endPullDownRefreshLately(100);
			 setTimeout(function() {
			    // mask.hideIt();
			 }, constant.ajaxDelay);
		}
	},
	_ajaxClone = function() {
		var obj = new Object(),
			key;
		for(key in _ajaxMethod) {
			obj[key] = _ajaxMethod[key];
		}
		return obj;
	},
	_ajaxFilter = function() {
		var param = arguments[0],
			_ajaxMethod = _ajaxClone(_ajaxMethod),
			token = LS.get('emmToken');
		//!param.show && mask.showIt();

		param.data = param.data || [{}];
		param.success = param.success || function() {};
		param.error = param.error || function() {};
		param.complete = param.complete || function() {};
		param.headers = param.headers;
		_ajaxMethod.param = param;
		_ajaxMethod.paramCache = $.extend({}, param);
		var paramData = Object.prototype.toString.call(param.data) == '[object String]' ? JSON.parse(param.data) : param.data;
		var CurPage = paramData.start;
		/*过滤重复数据*/
		if(CurPage != undefined) {
			if(CurPage == '0') {
				ajaxUrl = {};
			} else {
				if(ajaxUrl[paramData.start])
					return;
				else
					ajaxUrl[paramData.start] = true;
			}
		}
		_ajaxMethod.debug && console.log('url: ' + param.url);
		param.success = function() {
			var args = arguments;
			if(_ajaxMethod.debug) {
				console.log('param data: ', param.data, args);
				_ajaxMethod.successCallback(args);
			} else {
				try {
					console.log('param data: ', param.data, args);
					_ajaxMethod.successCallback(args);
				} catch(e) {
					console.log('success() error: ', e);
				}
			}
		}
		param.error = function() {
			var args = arguments;
			if(_ajaxMethod.debug) {
				_ajaxMethod.errorCallback(args);
			} else {
				try {
					_ajaxMethod.errorCallback(args);
				} catch(e) {
					console.log('error() error: ', e);
				}
			}
		}
		param.complete = function() {
			var args = arguments;
			if(_ajaxMethod.debug) {
				_ajaxMethod.completeCallback(args);
			} else {
				try {
					_ajaxMethod.completeCallback(args);
				} catch(e) {
					console.log('complete() error: ', e);
				}
			}
		}
		param.timeout = constant.ajaxTimeout;
		// _ajaxMethod.debug && console.log('ajax args: ', arguments);
		_ajax.apply(this, arguments)
	},
	_ajaxFilterWrap = function() {
		var arg = arguments;
		EventUtil.throttleFire(function() {
			_ajaxFilter.apply(null, arg);
		});
	};

//window.$.ajax = _ajaxFilterWrap;
window.appcan.request.ajax = _ajaxFilterWrap;

var Load = {
	loading: function(type) {
		if(type == 0) {
			$('.scrollbox').addClass('uhide');
		}

		var $el = $('body');
		var _html = '<div id="inLoaded"><img src="../../css/icons/icon-load.gif">';
		_html += '</img></div>';
		$el.append(_html);

		$('#inLoaded').on('cilick', function(e) {
			e.stopPropagation();
		});
	},
	finish:function() {
		$('.scrollbox').removeClass('uhide');
		$('#inLoaded').remove();
	}
}